package thread;

import java.util.PriorityQueue;

//任务
class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable task;
    private long time;
    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    public long getTime() {
        return this.time;
    }

    public void run() {
        task.run();
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
}

//定时器的实现
class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    //提交任务
    public void schedule(Runnable task, long delay) {
        synchronized (this) {
            MyTimerTask timerTask = new MyTimerTask(task, System.currentTimeMillis()+delay);
            queue.offer(timerTask);
            this.notify();
        }
    }

    //线程处理任务
    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized (this) {
                        while (queue.isEmpty()) {
                            this.wait();
                        }
                        MyTimerTask task = queue.peek();
                        if (System.currentTimeMillis() < task.getTime()) {
                            this.wait( task.getTime() - System.currentTimeMillis());
                        } else {
                            task.run();
                            queue.poll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }
}

public class Demo28 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
    }
}
